#include <miwidget-in.h>
#include <miwidget.h>

static SDL_Window *gWindow = NULL;
static SDL_Surface *gSurface = NULL;

void DrawPixel(SDL_Surface *s, int x, int y, Uint32 color)
{
    if (x < 0 || y < 0 || x >= s->w || y >= s->h)
        return;
    Uint32 *bufp;
    bufp = (Uint32 *)s->pixels + y*s->pitch/4 + x;
    *bufp = color;
}

void ReadPixel(SDL_Surface *s, int x, int y, Uint32 *color)
{
    if (x < 0 || y < 0 || x >= s->w || y >= s->h)
        return;
    Uint32 *bufp;
    bufp = (Uint32 *)s->pixels + y*s->pitch/4 + x;
    *color = *bufp;
}

void DrawRectFill(SDL_Surface *s, int x, int y, Uint32 w, Uint32 h, Uint32 color)
{
    int i, j;
    for (j = 0; j < h; j++) {
        for (i = 0; i < w; i++) {
            DrawPixel(s, x + i, y + j, color);
        }
    }
}

/**
 * support rect fill on window
 */
void miwidget_rectfill(int x, int y, uint32_t w, uint32_t h, uint32_t color)
{
    DrawRectFill(gSurface, x, y, w, h, color);
}

/**
 * support output pixel on window
 */
void miwidget_outpixel(int x, int y, uint32_t color)
{
    DrawPixel(gSurface, x, y, color);
}

/**
 * support output pixel on window
 */
void miwidget_inpixel(int x, int y, uint32_t *color)
{
    ReadPixel(gSurface, x, y, color);
}

int main(int argc, char *argv[])
{
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
        return -1;
    atexit(SDL_Quit);
    gWindow = SDL_CreateWindow("miwidget", 100, 100, WIN_WIDTH, WIN_HEIGHT, SDL_WINDOW_SHOWN);
    if (gWindow == NULL) {
        printf("create window failed!\n");
        return -1;
    }
    gSurface = SDL_GetWindowSurface(gWindow);
    miwidget_init();
    SDL_Event e;
    int quit = 0;
    while (!quit)
    {
        if (SDL_PollEvent(&e)) {
            switch (e.type)
            {
            case SDL_QUIT:
                quit = 1;
                break;
            case SDL_KEYDOWN:
                if (e.key.keysym.sym == SDLK_ESCAPE) {
                    quit = 1;
                }
            default:
                break;
            }
        }

        /* update to screen */
        usleep(1000);
        SDL_UpdateWindowSurface(gWindow);
    }
    
    return 0;
}